<!-- 搜索表单 -->
<template>
  <a-card :bordered="false">
    <!-- 表格 -->
    <ele-pro-table ref="tableRef" row-key="id" :columns="columns" resizable :datasource="datasource" :height="500"
      @update:selection="containerBillTableOnSelectionChange" :customRow="containerBillTableRowClick"
      v-model:current="containerBillCurrent" :scroll="{ x: 3500 }" cacheKey="containBill">
      <template #toolbar>
        <a-space>
          <a-button type="primary" @click="openEdit()" v-any-permission="['order:containerBill:order']">
            <template #icon>
              <plus-outlined />
            </template>
            <span>下单</span>
          </a-button>
          <a-popconfirm v-if="receivableVisiBle" v-any-permission="['order:containerBill:platReceive']"
            :title="billOfLading + '接单确认吗？'" @confirm="receivComfirm()">
            <a-button type="primary" v-any-permission="['order:containerBill:platReceive']">
              <template #icon>
                <plus-outlined />
              </template>
              <span>接单</span>
            </a-button>
          </a-popconfirm>
          <a-button v-if="carTeamVisiBle" @click="carTeamEdit()" type="primary"
            v-any-permission="['order:containerBill:carTeam']">
            <template #icon>
              <plus-outlined />
            </template>
            <span>指派车队</span>
          </a-button>
          <a-popconfirm v-if="containerBillCurrent.state != '结单'" :title="billOfLading + '现金单确认吗？'"
            @confirm="cashComfirm()">
            <a-button type="primary">
              <template #icon>
                <plus-outlined />
              </template>
              <span>{{ containerBillCurrent.cash == 1 ? '取消' : '' }}现金</span>
            </a-button>
          </a-popconfirm>
          <a-popconfirm v-if="containerBillCurrent.state != '结单'" :title="billOfLading + '落箱确认吗？'"
            @confirm="dropBoxComfirm()">
            <a-button type="primary">
              <template #icon>
                <plus-outlined />
              </template>
              <span>{{ containerBillCurrent.dropBox == 1 ? '取消' : '' }}落箱</span>
            </a-button>
          </a-popconfirm>
          <a-popconfirm v-if="containerBillCurrent.state != '结单'" :title="billOfLading + '预提确认吗？'"
            @confirm="withholdingComfirm()">
            <a-button type="primary">
              <template #icon>
                <plus-outlined />
              </template>
              <span>{{ containerBillCurrent.withholding == 1 ? '取消' : '' }}预提</span>
            </a-button>
          </a-popconfirm>
          <a-button v-if="substitutePhotoVisiBle" @click="substitutePhotoEdit()" type="primary"
            v-any-permission="['order:containerBill:substitutePhoto']">
            <template #icon>
              <plus-outlined />
            </template>
            <span>箱号封号</span>
          </a-button>
          <a-popconfirm v-any-permission="['order:containerBill:costBill']" v-if="costBillVisiBle"
            :title="billOfLading + '发起费用清单确认吗？'" @confirm="costBillComfirm()">
            <a-button type="primary" v-any-permission="['order:containerBill:costBill']">
              <template #icon>
                <plus-outlined />
              </template>
              <span>发起费用清单</span>
            </a-button>
          </a-popconfirm>
          <a-button v-if="trackVisiBle" @click="trackComfirm()" style="color: #ef5b9c;">
            <template #icon>
              <plus-outlined />
            </template>
            <span>历史轨迹</span>
          </a-button>
          <a-button v-if="containerBillCurrent.billOfLading != ''" @click="clipBoard()" style="color: #ffce7b;">
            <template #icon>
              <plus-outlined />
            </template>
            <span>复制</span>
          </a-button>
          <a-button v-if="containerBillCurrent.billOfLading != ''" @click="copyContainBill()" style="color: #76becc;">
            <template #icon>
              <plus-outlined />
            </template>
            <span>复制订单</span>
          </a-button>
          <a-button @click="containOceanApplyBtn()" style="color: #4e72b8;"
            v-any-permission="['order:containerBill:list']">
            <template #icon>
              <plus-outlined />
            </template>
            <span>关联表设置</span>
          </a-button>
          <a-button @click="exportsFinance()" type="primary" v-any-permission="['order:customer:exportsFinance']">
            <template #icon>
              <plus-outlined />
            </template>
            <span>财务导出</span>
          </a-button>
          <a-popconfirm :title="billOfLading + '结单取消确认吗？'"
            @confirm="cancleFinance()" v-any-permission="['order:customer:exportsFinance']">
            <a-button type="primary" v-any-permission="['order:customer:exportsFinance']">
              <template #icon>
                <plus-outlined />
              </template>
              <span>结单取消</span>
            </a-button>
          </a-popconfirm>
          <a-popconfirm :title="billOfLading + '确认结单吗？'"
            @confirm="finishFinance()" v-any-permission="['order:customer:exportsFinance']">
            <a-button type="primary" v-any-permission="['order:customer:exportsFinance']">
              <template #icon>
                <plus-outlined />
              </template>
              <span>结单</span>
            </a-button>
          </a-popconfirm>
          <div v-if="containerBillCurrent.billOfLading != ''">
            <a-tag color="cyan"
              v-if="containerBillCurrent.oceanId != 0 && containerBillCurrent.oceanId != null">海运</a-tag>
            <a-tag color="purple"
              v-if="containerBillCurrent.applyId != 0 && containerBillCurrent.applyId != null">报关</a-tag>
            <a-tag color="#87d068" v-if="containerBillCurrent.cash == 1">现金单</a-tag>
            <a-tag color="#87d068" v-if="containerBillCurrent.dropBox == 1">落箱</a-tag>
            <a-tag color="#87d068" v-if="containerBillCurrent.withholding == 1">预提</a-tag>
          </div>
        </a-space>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'factoryAddress'">
          <span v-html="factoryAddress_format(record.factoryAddress)"></span>
        </template>
        <template v-if="column.key === 'annex'">
          <template v-if="record.annex != '' && record.annex != null && record.annex.length > 3">
            <template v-for="(item2, index2) in JSON.parse(record.annex)" :key="index2">
              <div class="annex" @click="openFile(item2.url)">{{ index2 + 1 }}. {{ item2.name }}</div>
            </template>
          </template>
          <template v-else>
            <div></div>
          </template>
        </template>
        <template v-if="column.key === 'boxNumPic'">
          <template v-if="record.boxNumPic != ''">
            <template v-for="(item2, index2) in JSON.parse(record.boxNumPic)" :key="index2">
              <img class="sealnoPic" @click="openFile(item2.url)" :src="viewFile(item2.url)" />
            </template>
          </template>
        </template>
        <template v-if="column.key === 'sealnoPic'">
          <template v-if="record.sealnoPic != ''">
            <template v-for="(item2, index2) in JSON.parse(record.sealnoPic)" :key="index2">
              <img class="sealnoPic" @click="openFile(item2.url)" :src="viewFile(item2.url)" />
            </template>
          </template>
        </template>
        <template v-else-if="column.key === 'action' && record.state !== '结单'">
          <a-space>
            <a @click="openEdit(record)">修改</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定要删除此项吗？" @confirm="remove(record)">
              <a class="ele-text-danger">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </ele-pro-table>
  </a-card>
  <!-- 拖车运单添加、修改弹窗 -->
  <ele-modal :width="860" v-model:visible="containerBill_modal" :confirm-loading="loading"
    :title="isUpdate ? '修改拖车运单' : '新建拖车运单'" :body-style="{ paddingBottom: '8px' }" @ok="save" :maskClosable="false"
    :move-out="true" :resizable="false">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ md: { span: 4 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 20 }, sm: { span: 24 } }">
      <a-form-item label="客户名称" name="customer_val">
        <a-auto-complete v-model:value="form.customer_val" :options="customerOptions" placeholder="请输入"
          @select="customer_onSelect" @search="customer_onSearch" @blur="customer_blur" allow-clear />
      </a-form-item>
      <a-form-item label="装箱日期" name="factoryPackDate">
        <a-date-picker v-model:value="form.factoryPackDate" valueFormat="YYYY-MM-DD HH:mm" format="YYYY-MM-DD HH:mm"
          :show-time="{ defaultValue: dayjs('00:00', 'HH:mm') }" placeholder="请输入装箱日期(客户要求的装箱时间)" class="ele-fluid"
          allow-clear />
      </a-form-item>
      <a-form-item label="口岸" name="dock">
        <a-select v-model:value="form.dock" show-search placeholder="请输入口岸" :options="dock_options"
          :filter-option="dock_filter" @change="search" allow-clear></a-select>
      </a-form-item>
      <a-form-item label="加封地" name="sealedLand">
        <a-select v-model:value="form.sealedLand" show-search placeholder="请输入口岸" :options="sealedLand_options"
          :filter-option="sealedLand_filterOption" @change="search" allow-clear></a-select>
      </a-form-item>
      <a-form-item label="工厂地址1" name="factoryAddress1">
        <a-row>
          <a-col :span="23">
            <a-input allow-clear :maxlength="200" placeholder="请输入工厂地址" v-model:value="form.factoryAddress1"
              @blur="factoryTrim" autocomplete="off" />
          </a-col>
          <a-col :span="1">
            <div class="addFactory">
              <plus-circle-outlined class="button" @click="factory_index < 6 ? factory_index++ : false" />
            </div>
          </a-col>
        </a-row>
      </a-form-item>
      <a-form-item label="装箱人电话1" name="factoryPhone1">
        <a-row>
          <a-col :span="23">
            <a-input allow-clear :maxlength="200" placeholder="请输入装箱人电话" v-model:value="form.factoryPhone1"
              @blur="factoryTrim" autocomplete="off" />
          </a-col>
          <a-col :span="1">
            <div class="addFactory">
              <minus-circle-outlined class="button" @click="factory_index > 1 ? factory_index-- : false" />
            </div>
          </a-col>
        </a-row>
      </a-form-item>
      <a-form-item label="经纬度1" name="lonlat1" hidden>
        <a-input allow-clear :maxlength="200" placeholder="请输入经纬度" v-model:value="form.lonlat1" autocomplete="off" />
      </a-form-item>
      <a-form-item label="工厂地址2" name="factoryAddress2" v-if="factory_index > 1">
        <a-input allow-clear :maxlength="200" placeholder="请输入工厂地址" v-model:value="form.factoryAddress2"
          @blur="factoryTrim" autocomplete="off" />
      </a-form-item>
      <a-form-item label="装箱人电话2" name="factoryPhone2" v-if="factory_index > 1">
        <a-input allow-clear :maxlength="200" placeholder="请输入装箱人电话" v-model:value="form.factoryPhone2"
          @blur="factoryTrim" autocomplete="off" />
      </a-form-item>
      <a-form-item label="经纬度2" name="lonlat2" hidden v-if="factory_index > 1">
        <a-input allow-clear :maxlength="200" placeholder="请输入经纬度" v-model:value="form.lonlat2" autocomplete="off" />
      </a-form-item>
      <a-form-item label="工厂地址3" name="factoryAddress3" v-if="factory_index > 2">
        <a-input allow-clear :maxlength="200" placeholder="请输入工厂地址" v-model:value="form.factoryAddress3"
          @blur="factoryTrim" autocomplete="off" />
      </a-form-item>
      <a-form-item label="装箱人电话3" name="factoryPhone3" v-if="factory_index > 2">
        <a-input allow-clear :maxlength="200" placeholder="请输入装箱人电话" v-model:value="form.factoryPhone3"
          @blur="factoryTrim" autocomplete="off" />
      </a-form-item>
      <a-form-item label="经纬度3" name="lonlat3" hidden v-if="factory_index > 2">
        <a-input allow-clear :maxlength="200" placeholder="请输入经纬度" v-model:value="form.lonlat3" autocomplete="off" />
      </a-form-item>
      <a-form-item label="工厂地址4" name="factoryAddress4" v-if="factory_index > 3">
        <a-input allow-clear :maxlength="200" placeholder="请输入工厂地址" v-model:value="form.factoryAddress4"
          @blur="factoryTrim" autocomplete="off" />
      </a-form-item>
      <a-form-item label="装箱人电话4" name="factoryPhone4" v-if="factory_index > 3">
        <a-input allow-clear :maxlength="200" placeholder="请输入装箱人电话" v-model:value="form.factoryPhone4"
          @blur="factoryTrim" autocomplete="off" />
      </a-form-item>
      <a-form-item label="经纬度4" name="lonlat4" hidden v-if="factory_index > 3">
        <a-input allow-clear :maxlength="200" placeholder="请输入经纬度" v-model:value="form.lonlat4" autocomplete="off" />
      </a-form-item>
      <a-form-item label="工厂地址5" name="factoryAddress5" v-if="factory_index > 4">
        <a-input allow-clear :maxlength="200" placeholder="请输入工厂地址" v-model:value="form.factoryAddress5"
          @blur="factoryTrim" autocomplete="off" />
      </a-form-item>
      <a-form-item label="装箱人电话5" name="factoryPhone5" v-if="factory_index > 4">
        <a-input allow-clear :maxlength="200" placeholder="请输入装箱人电话" v-model:value="form.factoryPhone5"
          @blur="factoryTrim" autocomplete="off" />
      </a-form-item>
      <a-form-item label="经纬度5" name="lonlat5" hidden v-if="factory_index > 4">
        <a-input allow-clear :maxlength="200" placeholder="请输入经纬度" v-model:value="form.lonlat5" autocomplete="off" />
      </a-form-item>
      <a-form-item label="工厂地址6" name="factoryAddress6" v-if="factory_index > 5">
        <a-input allow-clear :maxlength="200" placeholder="请输入工厂地址" v-model:value="form.factoryAddress6"
          @blur="factoryTrim" autocomplete="off" />
      </a-form-item>
      <a-form-item label="装箱人电话6" name="factoryPhone6" v-if="factory_index > 5">
        <a-input allow-clear :maxlength="200" placeholder="请输入装箱人电话" v-model:value="form.factoryPhone6"
          @blur="factoryTrim" autocomplete="off" />
      </a-form-item>
      <a-form-item label="经纬度6" name="lonlat6" hidden v-if="factory_index > 5">
        <a-input allow-clear :maxlength="200" placeholder="请输入经纬度" v-model:value="form.lonlat6" autocomplete="off" />
      </a-form-item>
      <a-form-item label="提箱堆场" name="upYard">
        <a-auto-complete v-model:value="form.upYard_val" :options="upYardOptions" placeholder="请输入"
          @select="upYard_onSelect" @search="upYard_onSearch" @blur="upYard_blur" allow-clear />
        <!-- <a-input allow-clear :maxlength="200" placeholder="提箱堆场" v-model:value="form.upYard" /> -->
      </a-form-item>
      <a-form-item label="进港码头" name="arrivalPort">
        <a-auto-complete v-model:value="form.arrivalPort_val" :options="arrivalPortOptions" placeholder="请输入"
          @select="arrivalPort_onSelect" @search="arrivalPort_onSearch" @blur="arrivalPort_blur" allow-clear />
        <!-- <a-input allow-clear :maxlength="200" placeholder="进港码头" v-model:value="form.arrivalPort" /> -->
      </a-form-item>
      <a-form-item label="重量" name="weight">
        <a-input allow-clear :maxlength="200" placeholder="请输入重量" v-model:value="form.weight" autocomplete="off" />
      </a-form-item>
      <a-form-item label="箱型" name="boxType">
        <a-select v-model:value="form.boxType" show-search placeholder="请输入箱型" :options="boxType_options"
          :filter-option="boxType_filterOption" @change="search"></a-select>
      </a-form-item>
      <a-form-item label="船名" name="vessel">
        <a-input allow-clear :maxlength="200" placeholder="请输入船名" v-model:value="form.vessel" autocomplete="off" />
      </a-form-item>
      <a-form-item label="航次" name="voyage">
        <a-input allow-clear :maxlength="200" placeholder="请输入航次" v-model:value="form.voyage" autocomplete="off" />
      </a-form-item>
      <a-form-item label="箱号" name="boxNum">
        <a-input allow-clear :maxlength="200" placeholder="请输入箱号" v-model:value="form.boxNum" autocomplete="off" />
      </a-form-item>
      <a-form-item label="封号" name="sealno">
        <a-input allow-clear :maxlength="200" placeholder="请输入封号" v-model:value="form.sealno" autocomplete="off" />
      </a-form-item>
      <a-form-item label="提单号" name="billOfLading">
        <a-input allow-clear :maxlength="200" placeholder="请输入提单号" v-model:value="form.billOfLading" autocomplete="off" />
      </a-form-item>
      <a-form-item label="客户备注" name="customerRemark">
        <a-input allow-clear :maxlength="200" placeholder="请输入客户备注" v-model:value="form.customerRemark"
          autocomplete="off" />
      </a-form-item>
      <a-form-item label="平台备注" name="platRemark">
        <a-input allow-clear :maxlength="200" placeholder="请输入平台备注" v-model:value="form.platRemark" autocomplete="off" />
      </a-form-item>
      <a-form-item label="附件" name="annex">
        <a-upload-dragger v-model:file-list="annexFilelist" :customRequest="annexUploadFiles"
          @remove="annexUploadFilesRemove" :multiple="true">
          <p class="ant-upload-drag-icon">
            <inbox-outlined></inbox-outlined>
          </p>
          <p class="ant-upload-text">Click or drag file to this area to upload</p>
          <p class="ant-upload-hint">
            Support for a single or bulk upload. Strictly prohibit from uploading company data or other
            band files
          </p>
        </a-upload-dragger>
      </a-form-item>
    </a-form>
  </ele-modal>
  <!-- 指派车队添加、修改弹窗 -->
  <ele-modal :width="860" v-model:visible="carTeamVisible_modal" :confirm-loading="loading" :title="billOfLading + '指派车队'"
    :body-style="{ paddingBottom: '8px' }" @ok="carTeamUpdate" :maskClosable="false" :move-out="true" :resizable="false">
    <a-form ref="carTeamformRef" :model="form" :rules="carTeamRules" :label-col="{ md: { span: 4 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 20 }, sm: { span: 24 } }">
      <a-form-item label="车队" name="carTeam_val">
        <a-auto-complete v-model:value="form.carTeam_val" :options="carTeamOptions" placeholder="请输入车队"
          @select="carTeam_onSelect" @search="carTeam_onSearch" @blur="carTeam_blur" allow-clear />
      </a-form-item>
      <a-form-item label="车牌" name="carNo">
        <a-auto-complete v-model:value="form.carNo_val" :options="carNoOptions" placeholder="请输入司机"
          @select="carNo_onSelect" @search="carNo_onSearch" @change="carNo_onchange" @blur="carNo_blur" allow-clear />
      </a-form-item>
      <a-form-item label="司机" name="driver_val">
        <a-auto-complete v-model:value="form.driver_val" :options="driverOptions" placeholder="请输入司机"
          @select="driver_onSelect" @search="driver_onSearch" @change="driver_onchange" @blur="driver_blur" allow-clear />
      </a-form-item>
      <a-form-item label="司机电话" name="driverPhone">
        <a-input allow-clear :maxlength="200" placeholder="请输入司机电话" v-model:value="form.driverPhone" autocomplete="off" />
      </a-form-item>
      <a-form-item label="白卡号" name="whiteCard">
        <a-input allow-clear :maxlength="200" placeholder="请输入白卡号" v-model:value="form.whiteCard" autocomplete="off" />
      </a-form-item>
    </a-form>
  </ele-modal>
  <!-- 上传箱号封号预录入添加、修改弹窗 -->
  <ele-modal :width="860" v-model:visible="substitutePhotoVisible_modal" :confirm-loading="loading"
    :title="billOfLading + '上传箱号封号预录入'" :body-style="{ paddingBottom: '8px' }" @ok="substitutePhotoUpdate"
    :maskClosable="false" :move-out="true" :resizable="false">
    <a-form ref="substitutePhotoformRef" :model="form" :rules="substitutePhotoRules"
      :label-col="{ md: { span: 4 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 20 }, sm: { span: 24 } }">
      <a-form-item label="箱号" name="boxNum">
        <a-input allow-clear :maxlength="200" placeholder="请输入箱号" v-model:value="form.boxNum" autocomplete="off" />
      </a-form-item>
      <a-form-item label="箱号图片" name="boxNumPic_fileList">
        <a-upload v-model:file-list="form.boxNumPic_fileList" :customRequest="boxNumPicUploadFiles"
          list-type="picture-card" @preview="handlePreview" @remove="boxNumPicUploadFilesRemove">
          <div v-if="form.boxNumPic_fileList.length < 2">
            <plus-outlined />
            <div style="margin-top: 8px">Upload</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="封号" name="sealno">
        <a-input allow-clear :maxlength="200" placeholder="请输入封号" v-model:value="form.sealno" autocomplete="off" />
      </a-form-item>
      <a-form-item label="封号图片" name="sealnoPic_fileList">
        <a-upload v-model:file-list="form.sealnoPic_fileList" :customRequest="sealnoPicUploadFiles"
          list-type="picture-card" @preview="handlePreview" @remove="sealnoPicUploadFilesRemove">
          <div v-if="form.sealnoPic_fileList.length < 2">
            <plus-outlined />
            <div style="margin-top: 8px">Upload</div>
          </div>
        </a-upload>
      </a-form-item>
    </a-form>
  </ele-modal>
  <!-- 历史轨迹 弹窗 -->
  <ele-modal :width="1300" v-model:visible="trackVisible_modal" :confirm-loading="loading" title="轨迹展示及轨迹回放"
    :body-style="{ paddingBottom: '8px' }" @ok="trackUpdate" :maskClosable="false" :move-out="true" :resizable="false">
    <DemoTrack ref="demoTrackComp" :carNo_s="containerBillCurrent.carNo" :date1_s="date1_s" :date2_s="date2_s">
    </DemoTrack>
  </ele-modal>
  <!-- 拖车海运报关 关联表 弹窗 -->
  <ele-modal :width="1300" v-model:visible="containOceanApply_modal" :confirm-loading="loading" title="拖车海运报关 关联表"
    :body-style="{ paddingBottom: '8px' }" :maskClosable="false" :move-out="true" footer="" :resizable="false"
    position="center">
    <ContainerOceanApply ref="containOceanApplyComp"></ContainerOceanApply>
  </ele-modal>

  <!-- 应收应付分类导出财务报表 -->
  <ele-modal :width="460" v-model:visible="financeExportVisible" :confirm-loading="loading" :title="'应收应付分类导出财务报表'"
    position="center" :body-style="{ paddingBottom: '8px' }" @ok="financeExportSave" :maskClosable="false">
    <a-form :label-col="{ md: { span: 7 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
      <a-form-item label="客户" name="">
        <a-auto-complete v-model:value="financeCustomer.customer_val" :options="customerOptions" placeholder="请输入"
          @select="finance_customer_onSelect" @search="customer_onSearch" @blur="finance_customer_blur" allow-clear />
      </a-form-item>
      <a-form-item label="日期" name="factoryPackDate2">
        <a-range-picker v-model:value="factoryPackDate2" :format="YYYY - MM - DD" placeholder="" class="ele-fluid"
          :allow-clear="false" />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script setup>
import { ref, reactive, inject, watch, computed, toRaw } from 'vue';
import { toDateString, numberReg } from 'ele-admin-pro';
import dayjs from 'dayjs';
import { TIME_OUT } from '@/config/damon';

import useFormData from '@/utils/use-form-data';
import { message } from 'ant-design-vue';
import { UploadOutlined, PlusCircleOutlined, MinusCircleOutlined } from '@ant-design/icons-vue';
import { useRouter } from 'vue-router'

import {
  pageContainerBills, removeContainerBill, addContainerBill, updateContainerBill,
  platReceive, carTeam, substitutePhoto, upBox, costBill,
  payableVerify, receivableVerify, cash, dropBox, withholding,updateState
} from '@/api/order/containerBill';

import { listCustomersSel } from '@/api/order/customer';
import { listDriverSel, listCarNoSel } from '@/api/order/driver';
import { fileUpload } from '@/api/file';
import { listSettings } from '@/api/order/settings';
import { listMaintainFeeAttachsSel } from '@/api/order/maintainFeeAttach';

import { API_BASE_URL, TOKEN_HEADER_NAME } from '@/config/setting';
import { getToken } from '@/utils/token-util';
import useClipboard from 'vue-clipboard3'


import DemoTrack from '@/views/order/mapper/components/demo-track.vue'
import ContainerOceanApply from '@/views/order/containerBill/components/containerOceanApply.vue';



const props = defineProps({
  // processListDataS: Array,
})
let demoTrackComp = ref(null)
let processListData2 = reactive({ list: [] })
let receivableVisiBle = ref(false)
let carTeamVisiBle = ref(false)
let substitutePhotoVisiBle = ref(false)
let costBillVisiBle = ref(false)
let trackVisiBle = ref(false)
//权限判断 选择一条运单, 状态列表自动刷新同时自动调用流程显示按钮 权限的判断
let permissions = (processListDataS) => {
  processListData2.list = processListDataS.list
  receivableVisiBle_s(processListDataS)
  carTeamVisiBle_s(processListDataS)
  substitutePhotoVisiBle_s(processListDataS)
  costBillVisiBle_s(processListDataS)
  trackVisiBle_s(processListDataS)
}
//接单按钮显示
const receivableVisiBle_s = (processListDataS) => {
  receivableVisiBle.value = false
  if (!processListDataS || processListDataS.count == 0) { return false }
  receivableVisiBle.value = true
  if (processListDataS.list.findIndex(item => item.state == '接单') != -1) {
    receivableVisiBle.value = false
  }
}
//指派车队按钮显示
const carTeamVisiBle_s = (processListDataS) => {
  carTeamVisiBle.value = false
  if (!processListDataS || processListDataS.count == 0) { return false }
  let re = false, costBill = true
  if (processListDataS.list.findIndex(item => item.state == '接单') != -1) {
    re = true
  }
  if (processListDataS.list.findIndex(item => item.state == '发起费用清单') != -1) {
    costBill = false
  }
  if (re && costBill) {
    carTeamVisiBle.value = true
  }
}
//上传箱号封号预录入按钮显示
const substitutePhotoVisiBle_s = (processListDataS) => {
  substitutePhotoVisiBle.value = false
  if (!processListDataS || processListDataS.count == 0) { return false }
  let car = false, costBill = true
  if (processListDataS.list.findIndex(item => item.state == '接单') != -1) {
    car = true
  }
  if (processListDataS.list.findIndex(item => item.state == '发起费用清单') != -1) {
    costBill = false
  }
  if (car && costBill) {
    substitutePhotoVisiBle.value = true
  }
}
//发起费用清单按钮显示
const costBillVisiBle_s = (processListDataS) => {
  costBillVisiBle.value = false
  if (!processListDataS || processListDataS.count == 0) { return false }
  let car = false, costBill = true
  if (processListDataS.list.findIndex(item => item.state == '指派车队') != -1) {
    car = true
  }
  if (processListDataS.list.findIndex(item => item.state == '发起费用清单') != -1) {
    costBill = false
  }
  if (car && costBill) {
    costBillVisiBle.value = true
  }
}
//车辆轨迹按钮显示
const trackVisiBle_s = (processListDataS) => {
  trackVisiBle.value = false
  if (!processListDataS || processListDataS.count == 0) { return false }
  if (processListDataS.list.findIndex(item => item.state == '发起费用清单') != -1) {
    trackVisiBle.value = true
  }
}
const emit = defineEmits(['billIdSelect']);
// 表格实例
const tableRef = ref(null);

// 表格列配置
const columns = ref([
  {
    key: 'index',
    width: 35,
    align: 'center',
    fixed: 'left',
    hideInSetting: true,
    customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
  },
  {
    title: '客户名称',
    dataIndex: 'customer',
    resizable: true,
    width: 100,
    // fixed: 'left',
    // sorter: true
  },
  {
    title: '做箱日期',
    dataIndex: 'factoryPackDate',
    width: 100,
    // sorter: true
  },
  {
    title: '附件',
    dataIndex: 'annex',
    key: 'annex',
    width: 100,
    // sorter: true
  },
  {
    title: '订单状态',
    dataIndex: 'state',
    // sorter: true,
    width: 100,
    className: 'tableHiddle',
  },
  {
    title: '加封地',
    dataIndex: 'sealedLand',
    width: 80,
    // sorter: true
  },
  {
    title: '提单号',
    dataIndex: 'billOfLading',
    resizable: true,
    width: 140,
    // sorter: true
  },
  {
    title: '箱号',
    dataIndex: 'boxNum',
    width: 80,
    // sorter: true
  },
  {
    title: '封号',
    dataIndex: 'sealno',
    width: 80,
    // sorter: true
  },
  {
    title: '工厂信息',
    dataIndex: 'factoryAddress',
    resizable: true,
    key: 'factoryAddress',
    width: 250,
    // sorter: true
  },
  {
    title: '箱型',
    dataIndex: 'boxType',
    width: 50,
    // sorter: true
  },
  {
    title: '车队',
    dataIndex: 'carTeam',
    resizable: true,
    width: 80,
    // sorter: true
  },
  {
    title: '车牌',
    dataIndex: 'carNo',
    width: 80,
    // sorter: true
  },
  {
    title: '司机',
    dataIndex: 'driver',
    width: 60,
    // sorter: true
  },
  {
    title: '司机电话',
    dataIndex: 'driverPhone',
    width: 100,
    // sorter: true
  },
  {
    title: '重量(吨)',
    dataIndex: 'weight',
    width: 70,
    // sorter: true
  },
  {
    title: '提箱堆场',
    dataIndex: 'upYard',
    width: 80,
    // sorter: true
  },
  {
    title: '进港码头',
    dataIndex: 'arrivalPort',
    width: 80,
    // sorter: true
  },
  {
    title: '甩手备注',
    dataIndex: 'platRemark',
    width: 150,
    // sorter: true
  },
  {
    title: '口岸',
    dataIndex: 'dock',
    width: 60,
    // sorter: true
  },
  {
    title: '白卡号',
    dataIndex: 'whiteCard',
    width: 80,
    // sorter: true
  },
  {
    title: '船名',
    dataIndex: 'vessel',
    width: 100,
    // sorter: true
  },
  {
    title: '航次',
    dataIndex: 'voyage',
    width: 100,
    // sorter: true
  },
  {
    title: '箱号图片',
    dataIndex: 'boxNumPic',
    key: 'boxNumPic',
    width: 100,
    // sorter: true,
  },
  {
    title: '封号图片',
    dataIndex: 'sealnoPic',
    key: 'sealnoPic',
    width: 100,
    // sorter: true,
  },
  {
    title: '客户备注',
    dataIndex: 'customerRemark',
    width: 100,
    // sorter: true
  },
  // {
  //   title: '联系人',
  //   dataIndex: 'contacts',
  //   width: 100,
  //   // sorter: true
  // },
  // {
  //   title: '联系电话',
  //   dataIndex: 'contactsPhone',
  //   width: 100,
  //   // sorter: true
  // },
  {
    title: '业务员',
    dataIndex: 'salesman',
    width: 100,
    // sorter: true
  },
  {
    title: '操作',
    dataIndex: 'operater',
    width: 100,
    // sorter: true
  },
  {
    title: '下单时间',
    dataIndex: 'createTime',
    // sorter: true,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '操作',
    key: 'action',
    width: 100,
    align: 'center',
    fixed: 'right',
    hideInSetting: true
  }
]);

let datasource_index = true
// 表格数据源
const datasource = ({ page, limit, where, orders }) => {
  if (datasource_index) {
    where.factoryPackDateSearch1 = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
    where.factoryPackDateSearch2 = dayjs().add(1, 'day').format('YYYY-MM-DD')
  }

  return pageContainerBills({ ...where, ...orders, page, limit });
};

/* 搜索 */
const reload = (where) => {
  datasource_index = false
  tableRef?.value?.reload({ where });
};

/* 搜索 */
const reload2 = () => {
  tableRef?.value?.reload();
};

/*  重置 */
const reset = () => {
  resetFields();
  reload();
};

/* 删除单个 */
const remove = (record) => {
  const hide = message.loading('请求中..', 0);
  removeContainerBill(record.id).then((msg) => {
    hide();
    message.success(msg);
    reload();
  }).catch((e) => {
    hide();
    message.error(e.message);
  });
};

function openFile(op) {
  // 打开新窗口
  window.open(API_BASE_URL + '/file/' + op, '_blank');
}

function viewFile(op) {
  // 打开新窗口
  return API_BASE_URL + '/file/' + op
}

// 当前选中数据
let containerBillCurrent = ref({ 'billOfLading': '', 'son_type': 'containerBill', 'cash': 33 });

// 弹窗是否打开
const containerBill_modal = ref(false);

// 弹窗是否打开
const carTeamVisible_modal = ref(false);

// 弹窗是否打开
const substitutePhotoVisible_modal = ref(false);

// 弹窗是否打开
const financeExportVisible = ref(false);

// 弹窗是否打开
const trackVisible_modal = ref(false);

// 弹窗是否打开
const containOceanApply_modal = ref(false);

// 是否是修改
const isUpdate = ref(false);

// 提交状态
const loading = ref(false);

//
const formRef = ref(null);
//
const carTeamformRef = ref(null);
//
const substitutePhotoformRef = ref(null);

// 表单数据
const { form, resetFields: resetFormFields } = useFormData({
  id: undefined,
  customer: '',
  vessel: '',
  annex: '',
  carTeamId: 0,
  driverId: 0,
  boxNumPic: '',
  boxNumPic_fileList: [],
  sealnoPic: '',
  sealnoPic_fileList: [],
});
// document.addEventListener('mouseup' ,function () {
//     console.log(form);
// });
function factoryTrim() {
  // console.log(form.factoryPhone6);
  if (form?.factoryPhone1) form.factoryPhone1 = form.factoryPhone1.trim()
  if (form?.factoryAddress1) form.factoryAddress1 = form.factoryAddress1.trim()
  if (form?.factoryPhone2) form.factoryPhone2 = form.factoryPhone2.trim()
  if (form?.factoryAddress2) form.factoryAddress2 = form.factoryAddress2.trim()
  if (form?.factoryPhone3) form.factoryPhone3 = form.factoryPhone3.trim()
  if (form?.factoryAddress3) form.factoryAddress3 = form.factoryAddress3.trim()
  if (form?.factoryPhone4) form.factoryPhone4 = form.factoryPhone4.trim()
  if (form?.factoryAddress4) form.factoryAddress4 = form.factoryAddress4.trim()
  if (form?.factoryPhone5) form.factoryPhone5 = form.factoryPhone5.trim()
  if (form?.factoryAddress5) form.factoryAddress5 = form.factoryAddress5.trim()
  if (form?.factoryPhone6) form.factoryPhone6 = form.factoryPhone6.trim()
  if (form?.factoryAddress6) form.factoryAddress6 = form.factoryAddress6.trim()
}
// 表单验证规则
const rules = reactive({
  customer_val: [
    {
      required: true,
      message: '客户名称',
      type: 'string',
      trigger: 'blur'
    }
  ],
  dock: [
    {
      required: true,
      message: '请输入口岸',
      type: 'string',
      trigger: 'blur'
    }
  ],
  billOfLading: [
    {
      required: true,
      message: '请输入提单号',
      type: 'string',
      trigger: 'blur'
    }
  ],
  factoryPackDate: [
    {
      required: true,
      message: '请输入装箱日期',
      type: 'string',
      trigger: 'blur'
    }
  ],
  boxType: [
    {
      required: true,
      message: '请输入箱型',
      type: 'string',
      trigger: 'blur'
    }
  ],
  factoryAddress1: [{
    required: true, message: '请输入工厂地址1',
    type: 'string', trigger: 'blur'
  }],
  factoryPhone1: [{
    required: true, message: '请输入装箱人电话1',
    type: 'string', trigger: 'blur'
  }],
  factoryAddress2: [{
    required: true, message: '请输入工厂地址2',
    type: 'string', trigger: 'blur'
  }],
  factoryPhone2: [{
    required: true, message: '请输入装箱人电话2',
    type: 'string', trigger: 'blur'
  }],
  factoryAddress3: [{
    required: true, message: '请输入工厂地址3',
    type: 'string', trigger: 'blur'
  }],
  factoryPhone3: [{
    required: true, message: '请输入装箱人电话3',
    type: 'string', trigger: 'blur'
  }],
  factoryAddress4: [{
    required: true, message: '请输入工厂地址4',
    type: 'string', trigger: 'blur'
  }],
  factoryPhone4: [{
    required: true, message: '请输入装箱人电话4',
    type: 'string', trigger: 'blur'
  }],
  factoryAddress5: [{
    required: true, message: '请输入工厂地址5',
    type: 'string', trigger: 'blur'
  }],
  factoryPhone5: [{
    required: true, message: '请输入装箱人电话5',
    type: 'string', trigger: 'blur'
  }],
  factoryAddress6: [{
    required: true, message: '请输入工厂地址6',
    type: 'string', trigger: 'blur'
  }],
  factoryPhone6: [{
    required: true, message: '请输入装箱人电话6',
    type: 'string', trigger: 'blur'
  }],
});
// 表单验证规则 指派车队上传箱号封号预录入
const carTeamRules = reactive({
  carTeam_val: [
    {
      required: true,
      message: '请输入车队',
      type: 'string',
      trigger: 'blur'
    }
  ],
  // driver_val: [
  //   {
  //     required: true,
  //     message: '请输入司机',
  //     type: 'string',
  //     trigger: 'blur'
  //   }
  // ],
  // driverPhone: [
  //   {
  //     required: true,
  //     message: '请输入司机电话',
  //     type: 'string',
  //     trigger: 'blur'
  //   }
  // ],
  // carNo: [
  //   {
  //     required: true,
  //     message: '请输入车牌',
  //     type: 'string',
  //     trigger: 'blur'
  //   }
  // ],
});
// 表单验证规则 
const substitutePhotoRules = reactive({
  boxNum: [
    {
      required: true,
      message: '请输入箱号',
      type: 'string',
      trigger: 'blur'
    }
  ],
  sealno: [
    {
      required: true,
      message: '请输入封号',
      type: 'string',
      trigger: 'blur'
    }
  ],
});
//口岸
let dock_options = ref([])
listSettings({ 'typeM': 'dock_type' }).then(msg => {
  dock_options.value = msg
}).catch((e) => {
})
const dock_filter = (input, option) => {
  return (option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0);
};
//加封地
let sealedLand_options = ref([])
listSettings({ 'typeM': 'sealedLand' }).then(msg => {
  sealedLand_options.value = msg
}).catch((e) => {
})
const sealedLand_filterOption = (input, option) => {
  return (option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0);
};
//箱型
let boxType_options = ref([])
listSettings({ 'typeM': 'box_type' }).then(msg => {
  boxType_options.value = msg
}).catch((e) => {
})
const boxType_filterOption = (input, option) => {
  return (option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0);
};

let billOfLading = ref('')
let billId = ref('')
let containerBillTableRowClick = (record, index) => {
  return {
    onClick: (event) => {
      containerBillCurrent.value = record
      sendBillSelect()
    },
  }
}
let containerBillTableOnSelectionChange = (current_options) => {
  containerBillCurrent.value = current_options[0];
  sendBillSelect()
};

let sendBillSelect = (data) => {
  if (data != null && data != '' && data != undefined) {
    containerBillCurrent.value.state = data
  }
  // console.log(data,containerBillCurrent.value);
  billOfLading.value = containerBillCurrent.value.billOfLading ?? ''
  billId.value = containerBillCurrent.value.id
  // //containerBillFeeComp
  emit('billIdSelect', {
    'billId': containerBillCurrent.value.id,
    'invoice': {
      'company': containerBillCurrent.value.customer,
      'driver': containerBillCurrent.value.driver,
      'carTeam': containerBillCurrent.value.carTeam,
    },
    'state': containerBillCurrent.value.state,
  });
}

defineExpose({ permissions, reload, sendBillSelect });
let annexFilelist = ref([]);
function annexUploadFiles(info) {
  //开始真正上传
  //上传接口
  //调用公共上传方法
  fileUpload({ 'file': info.file, 'path2': 'chf_containerBill' }).then((msg) => {
    const upload_file_list_tmp_arr = {}
    upload_file_list_tmp_arr['uid'] = info.file.uid
    upload_file_list_tmp_arr['name'] = info.file.name
    upload_file_list_tmp_arr['status'] = 'done'
    upload_file_list_tmp_arr['url'] = msg.data.path + "?path2=chf_containerBill"
    let arr = form.annex == '' ? [] : JSON.parse(form.annex)
    arr.push(upload_file_list_tmp_arr)
    form.annex = JSON.stringify(arr)

    annexFilelist.value == undefined || annexFilelist.value.map(element => {
      element.status = 'done'
      element.url = API_BASE_URL + '/file/' + element.url
    })
    message.success('上传成功');

  }).catch((e) => {
    message.error(e.message);
  });
}
let annexUploadFilesRemove = info => {
  let arr = JSON.parse(form.annex)
  arr.splice(arr.findIndex(item => item.uid == info.uid), 1)
  form.annex = JSON.stringify(arr)
}


const fileUploadOpenForm = (record) => {
  annexFilelist.value = []
  if (record != undefined) {
    if (record.annex != '') {
      annexFilelist.value = [...JSON.parse(record.annex)]
    }
  }
}

//防止重复刷新
//客户下拉列表
let customer_m_timeout = 0
const customerOptions = ref([]);
const customer_onSearch = searchText => {
  clearTimeout(customer_m_timeout)
  customer_m_timeout = setTimeout(() => {
    listCustomersSel({ 'name': searchText, type: '货代' }).then(msg => {
      customerOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
const customer_onSelect = (value2, option2) => {
  // let a = customerOptions.value.find((item)=> {return item.value=value})
  form.customer_val = option2.label
  form.customer = option2.label
  form.customerId = option2.value
};
const customer_m_change = (value2) => {
  // let a = customerOptions.value.find((item)=> {return item.value=value2})
  // form.customer_val=a.label
  // form.customer=a.label
};
const customer_blur = () => {
  form.customer_val = form.customer
};
// 应收应付分类导出财务报表  客户下拉列表
let financeCustomer = ref({ customer_val: '', customer: '', customerId: '', abbreviation: '' })
const finance_customer_onSelect = (value2, option2) => {
  financeCustomer.value.customer_val = option2.label
  financeCustomer.value.customer = option2.label
  financeCustomer.value.customerId = option2.value
  financeCustomer.value.abbreviation = option2.abbreviation
};
const finance_customer_blur = () => {
  if (financeCustomer.value.customer_val) {
    financeCustomer.value.customer_val = financeCustomer.value.customer
  } else {
    financeCustomer.value.customer_val = ''
    financeCustomer.value.customer = ''
    financeCustomer.value.customerId = ''
    financeCustomer.value.abbreviation = ''
  }
};
//车队下拉
const carTeamOptions = ref([]);
const carTeam_onSearch = searchText => {
  clearTimeout(customer_m_timeout)
  customer_m_timeout = setTimeout(() => {
    listCustomersSel({ 'name': searchText, type: '车队' }).then(msg => {
      carTeamOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
const carTeam_onSelect = (value2, option2) => {
  // let a = carTeamOptions.value.find((item)=> {return item.value=value})
  form.carTeam_val = option2.label
  form.carTeam = option2.label
  form.carTeamId = option2.value
};
const carTeam_blur = () => {
  form.carTeam_val = form.carTeam
};
//司机下拉
const driverOptions = ref([]);
const driver_onSearch = searchText => {
  clearTimeout(customer_m_timeout)
  customer_m_timeout = setTimeout(() => {
    listDriverSel({ 'name': searchText, carTeamId: form.carTeamId }).then(msg => {
      driverOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
const driver_onSelect = (value2, option2) => {
  // let a = driverOptions.value.find((item)=> {return item.value=value})
  form.driver_val = option2.label
  form.driverId = option2.value
  form.driver = option2.label
  form.driverPhone = option2.phone
  form.carNo = option2.carNo
  form.carNo_val = option2.carNo
  form.whiteCard = option2.whiteCard
};
const driver_onchange = (value2, option2) => {
  // let a = driverOptions.value.find((item)=> {return item.value=value})
  form.driver_val = value2
  form.driverId = 0
  form.driver = value2
};
const driver_blur = () => {
  if (form.driver_val != form.driver) {
    form.driverId = 0
  }
};
//车牌下拉
const carNoOptions = ref([]);
const carNo_onSearch = searchText => {
  clearTimeout(customer_m_timeout)
  customer_m_timeout = setTimeout(() => {
    listCarNoSel({ 'carNo': searchText, carTeamId: form.carTeamId }).then(msg => {
      carNoOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
const carNo_onSelect = (value2, option2) => {
  // let a = carNoOptions.value.find((item)=> {return item.value=value})
  form.carNo_val = option2.label
  form.driverId = option2.value
  form.driver = option2.name
  form.driver_val = option2.name
  form.driverPhone = option2.phone
  form.carNo = option2.carNo
  form.whiteCard = option2.whiteCard
};
const carNo_onchange = (value2, option2) => {
  // let a = driverOptions.value.find((item)=> {return item.value=value})
  form.carNo_val = value2
  form.carNo = value2
};
const carNo_blur = () => {

};
//提箱堆场下拉
const upYardOptions = ref([]);
const upYard_onSearch = searchText => {
  clearTimeout(customer_m_timeout)
  customer_m_timeout = setTimeout(() => {
    listMaintainFeeAttachsSel({ 'name': searchText, 'yardDock': '堆场' }).then(msg => {
      upYardOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
const upYard_onSelect = (value2, option2) => {
  // let a = upYardOptions.value.find((item)=> {return item.value=value})
  form.upYard_val = option2.label
  form.upYard = option2.label
  form.efYard = option2.longitude ? (option2.longitude + ',' + option2.latitude) : '0,0'
};
const upYard_blur = () => {
  form.upYard_val = form.upYard
};

//进港码头下拉
const arrivalPortOptions = ref([]);
const arrivalPort_onSearch = searchText => {
  clearTimeout(customer_m_timeout)
  customer_m_timeout = setTimeout(() => {
    listMaintainFeeAttachsSel({ 'name': searchText, 'yardDock': '港口' }).then(msg => {
      arrivalPortOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
const arrivalPort_onSelect = (value2, option2) => {
  // let a = upYardOptions.value.find((item)=> {return item.value=value})
  form.arrivalPort_val = option2.label
  form.arrivalPort = option2.label
  form.efDock = option2.longitude ? (option2.longitude + ',' + option2.latitude) : '0,0'
};
const arrivalPort_blur = () => {
  form.arrivalPort_val = form.arrivalPort
};



let factory_index = ref(1)
// watch(factory_index, (val) => {
//   console.log('value', val);
// });
/* 打开编辑弹窗 */
const openEdit = (record) => {
  resetFormFields();
  factory_index.value = 1
  formRef.value?.clearValidate();
  containerBillCurrent.value = record ?? {};
  if (record == undefined) {
    form.customer_val = ''
  } else {
    form.customer_val = record.customer
    factoryAddressList_openForm(record.factoryAddress)
  }
  containerBill_modal.value = true;
  Object.assign(form, record ?? {});
  fileUploadOpenForm(record)
  isUpdate.value = !!record;
  form.upYard_val = form.upYard
  form.arrivalPort_val = form.arrivalPort
};
const carTeamEdit = () => {
  resetFormFields();
  carTeamformRef.value?.clearValidate();
  carTeamVisible_modal.value = true
  Object.assign(form, containerBillCurrent.value);
  if (form.carTeam == null) {
    form.carTeamId = 0
    form.carTeam_val = ''
  } else {
    form.carTeam_val = form.carTeam
  }
  if (form.driver == null) {
    form.driverId = 0
    form.driver_val = ''
    form.carNo_val = ''
  } else {
    form.driver_val = form.driver
    form.carNo_val = form.carNo
  }
}
//箱号封号
const substitutePhotoEdit = () => {
  resetFormFields();
  substitutePhotoformRef.value?.clearValidate();
  substitutePhotoVisible_modal.value = true
  Object.assign(form, containerBillCurrent.value);
  substitutePhoto_fileUploadOpenForm()
  if (form.carTeam == null) {
    form.carTeamId = 0
    form.carTeam_val = ''
  } else {
    form.carTeam_val = form.carTeam
  }
  if (form.driver == null) {
    form.driverId = 0
    form.driver_val = ''
  } else {
    form.driver_val = form.driver
  }
}

let date1_s = ref('')
let date2_s = ref('')
//历史轨迹
const trackComfirm = () => {
  trackVisible_modal.value = true
  let date1 = '', date2 = '', upBoxRet = true, costRet = true
  processListData2.list.forEach((ele) => {
    if (ele.state == '指派车队' && upBoxRet) {
      date1 = ele.createTime
    }
    if (ele.state == '提箱') {
      date1 = ele.createTime
      upBoxRet = false
    }
    if (ele.state == '进港') {
      date2 = ele.createTime
      costRet = false
    }
    if (ele.state == '发起费用清单' && costRet) {
      date2 = ele.createTime
    }
  })
  date1_s = date1
  date2_s = date2
}
//https://blog.csdn.net/weixin_45691320/article/details/125767207
const { toClipboard } = useClipboard()
const clipBoard = () => {
  let t1 = '装箱时间: ' + (containerBillCurrent.value.factoryPackDate ?? '')
    + '\r客户名称: ' + (containerBillCurrent.value.customer ?? '')
    + '\r船名航次:' + (containerBillCurrent.value.vessel ?? '') + ' ' + (containerBillCurrent.value.voyage ?? '')
    + '\r提单号:' + (containerBillCurrent.value.billOfLading ?? '')
    + '\r箱号:' + (containerBillCurrent.value.boxNum ?? '')
    + '\r封号:' + (containerBillCurrent.value.sealno ?? '')
    + '\r箱型:' + (containerBillCurrent.value.boxType ?? '')
    + '\r重量:' + (containerBillCurrent.value.weight ?? '')
    + '\r司机:' + (containerBillCurrent.value.driver ?? '')
    + '\r司机电话:' + (containerBillCurrent.value.driverPhone ?? '')
    + '\r司机车牌:' + (containerBillCurrent.value.carNo ?? '')
  if (containerBillCurrent.value.whiteCard != '' && containerBillCurrent.value.whiteCard != undefined && containerBillCurrent.value.whiteCard != null) {
    t1 += '\r白卡号:' + (containerBillCurrent.value.whiteCard ?? '')
  }
  t1 += '\r提箱堆场:' + (containerBillCurrent.value.upYard ?? '')
    + '\r进港码头:' + (containerBillCurrent.value.arrivalPort ?? '')
  if (containerBillCurrent.value.factoryAddress != '' && containerBillCurrent.value.factoryAddress != undefined && containerBillCurrent.value.factoryAddress != null) {
    let fa = JSON.parse(containerBillCurrent.value.factoryAddress)
    let index = 0
    fa.forEach(element => {
      index++
      t1 += '\r工厂信息' + index + ': ' + (element.factoryAddress ?? '') + ' ' + (element.factoryPhone ?? '')
    });
  }
  console.log(containerBillCurrent.value.customerRemark);
  if (containerBillCurrent.value.customerRemark) {
    t1 += '\r客户备注:' + (containerBillCurrent.value.customerRemark ?? '')
  }
  toClipboard(t1)
  message.success('复制成功!');
}
const copyContainBill = () => {
  resetFormFields();
  factory_index.value = 1
  formRef.value?.clearValidate();
  form.customer_val = containerBillCurrent.value.customer
  factoryAddressList_openForm(containerBillCurrent.value.factoryAddress)
  containerBill_modal.value = true;
  Object.assign(form, containerBillCurrent.value ?? {});
  fileUploadOpenForm(containerBillCurrent.value)
  form.boxNum = ''
  form.boxNumPic = ''
  form.boxNumPic_fileList = []
  form.sealno = ''
  form.sealnoPic = ''
  form.sealnoPic_fileList = []
  form.carTeam_val = ''
  form.carTeam = ''
  form.carNo = ''
  form.driver = ''
  form.driverPhone = ''
  form.whiteCard = ''
  form.upYard = ''
  form.upYard_val = ''
  form.arrivalPort = ''
  form.arrivalPort_val = ''
  form.annex = ''
  annexFilelist.value = []
  isUpdate.value = false;
}
let containOceanApplyComp = ref(null)
const containOceanApplyBtn = () => {
  containOceanApply_modal.value = true;
  setTimeout(() => {
    // containerBillCurrent.value.son_type = 'containerBill'
    containOceanApplyComp.value.removeContaiOceanApplyFormData()
    // containOceanApplyComp.value.onContainerBillSelect(containerBillCurrent.value)
  }, 1000);
}


//excel导出
function exportsFinance() {
  financeExportVisible.value = true
}
let factoryPackDate2 = ref([
  dayjs().startOf('month'),
  dayjs().endOf('month'),
  // dayjs().add(2, 'month'),
])

function getDate_self(op) {
  let monght_s = op.getMonth() + 1
  let day_s = op.getDate()
  if (monght_s < 10) { monght_s = '0' + monght_s }
  if (day_s < 10) { day_s = '0' + day_s }
  return op.getFullYear() + '-' + monght_s + '-' + day_s
}
/* 客户费用导出 */
const financeExportSave = () => {
  if (factoryPackDate2.value == null) {
    factoryPackDate2.value = []
  }
  if (factoryPackDate2.value.length > 0) {
    let date1 = getDate_self(new Date(factoryPackDate2.value[0]))
    let date2 = getDate_self(new Date(factoryPackDate2.value[1]))
    let dataStr = '?date1=' + date1 + '&date2=' + date2
      + '&customer=' + financeCustomer.value.customer + '&customerAbbreviation=' + financeCustomer.value.abbreviation
    let url = API_BASE_URL + '/order/containerBill/exportsFinance' + dataStr
    var xhr = new XMLHttpRequest();
    xhr.open("get", url, true); // get、post都可
    xhr.responseType = "blob";  // 转换流
    xhr.setRequestHeader(TOKEN_HEADER_NAME, getToken()); // token键值对
    xhr.onload = function () {
      if (this.status == 200) {
        var blob = this.response;
        var a = document.createElement("a")
        var url = window.URL.createObjectURL(blob)
        a.href = url
        a.download = "财务账单：" + date1 + "到" + date2 + ".xlsx"  // 文件名
      }
      a.click()
      window.URL.revokeObjectURL(url)
    }
    xhr.send();
    message.success('导出成功');
    financeExportVisible.value = false
  } else {
  }
};

/* 取消结单 */
const cancleFinance = () => {
  updateState({id: containerBillCurrent.value.id, state: '应收费用审核'}).then((msg) => {
      message.success(msg);
      reload2();
    }).catch((e) => {
      message.error(e.message);
    });
};

/* 结单 */
const finishFinance = () => {
  updateState({id: containerBillCurrent.value.id, state: '结单'}).then((msg) => {
      message.success(msg);
      reload2();
    }).catch((e) => {
      message.error(e.message);
    });
};

const substitutePhoto_fileUploadOpenForm = () => {
  form.boxNumPic_fileList = []
  form.sealnoPic_fileList = []
  if (containerBillCurrent.value.boxNumPic != '' && containerBillCurrent.value.boxNumPic != null) {
    let t_list = JSON.parse(containerBillCurrent.value.boxNumPic)
    t_list.map(element => { element.url = API_BASE_URL + '/file/' + element.url })
    form.boxNumPic_fileList = [...t_list]
  }
  if (containerBillCurrent.value.sealnoPic != '' && containerBillCurrent.value.sealnoPic != null) {
    let t_list = JSON.parse(containerBillCurrent.value.sealnoPic)
    t_list.map(element => { element.url = API_BASE_URL + '/file/' + element.url })
    form.sealnoPic_fileList = [...t_list]
  }
}

let factoryAddress_format = (data) => {
  if (data == null || data == '') return ''
  let list_temp = JSON.parse(data)
  let str = ''
  for (let val of list_temp) {
    str += val.factoryAddress + '  ' + val.factoryPhone + '</br>'
  }
  return str
}

function factoryAddressList_openForm(l_temp) {
  if (l_temp == null || l_temp == '' || l_temp == undefined) return
  l_temp = JSON.parse(l_temp)
  factory_index.value = l_temp.length
  for (let i = 0; i < factory_index.value; i++) {
    if (factory_index.value > i) {
      form['factoryAddress' + (i + 1)] = l_temp[i].factoryAddress
      form['factoryPhone' + (i + 1)] = l_temp[i].factoryPhone
      form['lonlat' + (i + 1)] = l_temp[i].lonlat
    }
  }
}

function factoryAddressList_saveAction() {
  let l_temp = []
  for (let i = 0; i < factory_index.value; i++) {
    if (factory_index.value > i) {
      l_temp.push({ "factoryAddress": form['factoryAddress' + (i + 1)], "factoryPhone": form['factoryPhone' + (i + 1)], "longitude": form['lonlat' + (i + 1)]?.split(',')[0], "latitude": form['lonlat' + (i + 1)]?.split(',')[1] })
    } else {
      return
    }
  }
  return JSON.stringify(l_temp)
}
/* 保存编辑 */
const save = () => {
  if (!formRef.value) {
    return;
  }
  form.factoryAddress = factoryAddressList_saveAction()
  formRef.value.validate().then(() => {
    loading.value = true;
    const saveOrUpdate = isUpdate.value ? updateContainerBill : addContainerBill;
    saveOrUpdate(form).then((msg) => {
      loading.value = false;
      message.success(msg);
      containerBill_modal.value = false;
      reload2();
      containerBillCurrent.value = { 'billOfLading': '' }
      emit('billIdSelect', {
        'billId': 0,
        'invoice': {
          'company': '',
          'driver': '',
        },
        'state': '',
      });
    }).catch((e) => {
      loading.value = false;
      message.error(e.message);
    });
  }).catch(() => {
  });
};
//接单 方法
const receivComfirm = () => {
  platReceive({ 'id': billId.value, 'state': '接单' }).then((msg) => {
    message.success('接单成功');
    reload2()
    sendBillSelect()
  }).catch((e) => {
    message.error(e.message);
  });
}
//现金单 方法
const cashComfirm = () => {
  let num = containerBillCurrent.value.cash == 1 ? 0 : 1
  cash({ 'id': billId.value, "cash": num }).then((msg) => {
    message.success('修改成功');
    containerBillCurrent.value.cash = num
    reload2()
    sendBillSelect()
  }).catch((e) => {
    message.error(e.message);
  });
}
//落箱 方法
const dropBoxComfirm = () => {
  let num = containerBillCurrent.value.dropBox == 1 ? 0 : 1
  dropBox({ 'id': billId.value, "dropBox": num }).then((msg) => {
    message.success('修改成功');
    containerBillCurrent.value.dropBox = num
    reload2()
    sendBillSelect()
  }).catch((e) => {
    message.error(e.message);
  });
}
//预提 方法
const withholdingComfirm = () => {
  let num = containerBillCurrent.value.withholding == 1 ? 0 : 1
  withholding({ 'id': billId.value, "withholding": num }).then((msg) => {
    message.success('修改成功');
    containerBillCurrent.value.withholding = num
    reload2()
    sendBillSelect()
  }).catch((e) => {
    message.error(e.message);
  });
}
//指派车队 保存方法
const carTeamUpdate = () => {
  if (!carTeamformRef.value) {
    return;
  }
  carTeamformRef.value.validate().then(() => {
    if (form.driver_val == '') {
      form.driverId = 0
      form.driver = ''
      form.carNo = ''
    }
    loading.value = true;
    carTeam(form).then((msg) => {
      loading.value = false;
      message.success(msg);
      carTeamVisible_modal.value = false
      reload2()
      sendBillSelect()
    }).catch((e) => {
      loading.value = false;
      message.error(e.message)
    });
  }).catch(() => {
  });
}

//上传箱封号 保存方法
const substitutePhotoUpdate = () => {
  if (!substitutePhotoformRef.value) {
    return;
  }
  substitutePhotoformRef.value.validate().then(() => {
    loading.value = true;
    substitutePhoto(form).then((msg) => {
      loading.value = false;
      message.success(msg);
      substitutePhotoVisible_modal.value = false
      containerBillCurrent.value={ 'billOfLading': '', 'son_type': 'containerBill', 'cash': 33 }
      reload2()
      sendBillSelect()
    }).catch((e) => {
      loading.value = false;
      message.error(e.message);
    });
  }).catch(() => {
  });
}

//发起费用清单 方法
const costBillComfirm = () => {
  platReceive({ 'id': billId.value, 'state': '发起费用清单' }).then((msg) => {
    message.success('发起费用清单成功');
    reload2()
    sendBillSelect()
  }).catch((e) => {
    message.error(e.message);
  });
}
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');

const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

const handlePreview = async file => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};

let boxNumPicUploadFiles = (info) => {
  //开始真正上传
  //上传接口
  //调用公共上传方法
  fileUpload({ 'file': info.file, 'path2': 'chf_containerBill' }).then((msg) => {
    const upload_file_list_tmp_arr = {}
    upload_file_list_tmp_arr['uid'] = info.file.uid
    upload_file_list_tmp_arr['name'] = info.file.name
    upload_file_list_tmp_arr['status'] = 'done'
    upload_file_list_tmp_arr['url'] = msg.data.path + "?path2=chf_containerBill"
    let arr = (form.boxNumPic == '' || form.boxNumPic == null) ? [] : JSON.parse(form.boxNumPic)
    arr.push(upload_file_list_tmp_arr)
    form.boxNumPic = JSON.stringify(arr)

    form.boxNumPic_fileList == undefined || form.boxNumPic_fileList.map(element => {
      element.status = 'done'
      // element.url = API_BASE_URL + '/file/' + element.url
    })
    message.success('上传成功');
  }).catch((e) => {
    message.error(e.message);
  });
}

let boxNumPicUploadFilesRemove = info => {
  let arr = JSON.parse(form.boxNumPic)
  arr.splice(arr.findIndex(item => item.uid == info.uid), 1)
  form.boxNumPic = JSON.stringify(arr)
  console.log(form.boxNumPic);
}

let sealnoPicUploadFiles = (info) => {
  //开始真正上传
  //上传接口
  //调用公共上传方法
  fileUpload({ 'file': info.file, 'path2': 'chf_containerBill' }).then((msg) => {
    const upload_file_list_tmp_arr = {}
    upload_file_list_tmp_arr['uid'] = info.file.uid
    upload_file_list_tmp_arr['name'] = info.file.name
    upload_file_list_tmp_arr['status'] = 'done'
    upload_file_list_tmp_arr['url'] = msg.data.path + "?path2=chf_containerBill"
    let arr = (form.sealnoPic == '' || form.sealnoPic == null) ? [] : JSON.parse(form.sealnoPic)
    arr.push(upload_file_list_tmp_arr)
    form.sealnoPic = JSON.stringify(arr)

    form.sealnoPic_fileList == undefined || form.sealnoPic_fileList.map(element => {
      element.status = 'done'
    })
    message.success('上传成功');
  }).catch((e) => {
    message.error(e.message);
  });
}

let sealnoPicUploadFilesRemove = info => {
  let arr = JSON.parse(form.sealnoPic)
  arr.splice(arr.findIndex(item => item.uid == info.uid), 1)
  form.sealnoPic = JSON.stringify(arr)
}
</script>

<style lang="less" scoped>
.annex {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;

  cursor: pointer;
  color: #426ab3;
}

.addFactory {
  display: flex;
  justify-content: flex-end;
  align-items: center;

  height: 100%;

  .button {
    color: red;
    font-size: 20px;
    margin-left: 15px;
    cursor: pointer;
  }
}

.sealnoPic {
  width: 25px;
  height: 18px;
}
</style>
